<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from 'element-plus';
import clueApi from '../api/clue';
import { useActivityStore } from '@/stores/activity';

// 路由实例
const router = useRouter();

// 搜索条件
const searchParams = ref({
  clueId: "",
  phone: "",
  channel: "",
});

// 线索池数据
const cluePoolList = ref([]);

// 加载状态
const loading = ref(false);

// 模态框显示状态
const dialogVisible = ref({
  viewClue: false,
  assignClue: false
});

// 当前查看的线索
const currentClue = ref({});

// 分配线索表单
const assignForm = ref({
  userId: ''
});

// 用户列表（实际应该从API获取）
const userList = ref([
  { label: '销售1', value: '1' },
  { label: '销售2', value: '2' },
  { label: '销售3', value: '3' }
]);

// 导入公共工具函数
import { formatGender, formatStatus, formatSubject, formatLevel, formatDateTime, processTrackRecords, channelOptions, getLevelColorStyle } from '../utils/clueUtils';

// 获取活动store
const activityStore = useActivityStore()

// 格式化渠道
const formatChannel = (value) => {
  if (!value) return '';
  const option = channelOptions.find(opt => opt.value === Number(value));
  return option ? option.label : '';
};

// 格式化活动名称
const formatActivityName = (activityId) => {
  return activityStore.getActivityNameById(activityId)
};

// 处理跟进记录数据
const processedTrackRecords = computed(() => {
  return processTrackRecords(currentClue.value.trackRecords || []);
});

// 获取线索池数据
const getCluePoolData = async () => {
  loading.value = true;
  try {
    const response = await clueApi.getCluePool({
      clueId: searchParams.value.clueId,
      phone: searchParams.value.phone,
      channel: searchParams.value.channel,
      page: currentPage.value,
      pageSize: pageSize.value
    });
    cluePoolList.value = response.data.rows || [];
    totalCount.value = response.data.total || 0;
  } catch (error) {
    ElMessage.error('获取线索池数据失败');
  } finally {
    loading.value = false;
  }
};

// 获取线索详情
const getClueDetail = async (id) => {
  try {
    const response = await clueApi.getClueById(id);
    return response.data;
  } catch (error) {
    ElMessage.error('获取线索详情失败');
    return null;
  }
};

// 分配线索
const assignClueToUser = async () => {
  if (!assignForm.value.userId) {
    ElMessage.warning('请选择分配人员');
    return;
  }
  
  try {
    await clueApi.assignClue(currentClue.value.id, assignForm.value.userId);
    ElMessage.success('线索分配成功');
    dialogVisible.value.assignClue = false;
    // 重新获取线索池数据
    getCluePoolData();
  } catch (error) {
    ElMessage.error('线索分配失败');
  }
};

// 打开分配线索对话框
const openAssignClueDialog = (clue) => {
  currentClue.value = { ...clue };
  assignForm.value.userId = '';
  dialogVisible.value.assignClue = true;
};

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    clueId: '',
    phone: '',
    channel: ''
  };
  currentPage.value = 1;
  getCluePoolData();
};

// 搜索
const search = () => {
  currentPage.value = 1;
  getCluePoolData();
};

// 查看线索
const viewClue = async (clue) => {
  dialogVisible.value.viewClue = true;
  try {
    const response = await clueApi.getClueById(clue.id);
    currentClue.value = response.data;
    // 确保跟进记录字段存在
    if (!currentClue.value.followRecords) {
      currentClue.value.followRecords = [];
    }
  } catch (error) {
    ElMessage.error('获取线索详情失败');
  }
};

// 分页相关变量
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  getCluePoolData();
};

// 处理当前页码变化
const handleCurrentChange = (current) => {
  currentPage.value = current;
  getCluePoolData();
};

// 生命周期钩子
onMounted(async () => {
  // 如果活动数据未初始化，先初始化
  if (!activityStore.initialized) {
    await activityStore.initializeActivities()
  }
  getCluePoolData();
});
</script>

<template>
  <div class="clue-pool-view">
    <div class="page-header">
      <h2>线索池</h2>
    </div>

    <!-- 搜索条件区域 -->
    <div class="search-container">
      <el-form :inline="true" size="small">
        <el-form-item label="线索ID:">
          <el-input
            v-model="searchParams.clueId"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:">
          <el-input
            v-model="searchParams.phone"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="渠道来源:">
          <el-select v-model="searchParams.channel" placeholder="请选择">
            <el-option v-for="option in channelOptions" :key="option.value" :label="option.label" :value="String(option.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 使用预设样式类来确保滚动条和分页正确显示 -->
    <div class="content-wrapper">
      <!-- 表格内容容器 -->
      <div class="table-wrapper">
        <el-table :data="cluePoolList" stripe :loading="loading">
            <el-table-column
              prop="id"
              label="线索ID"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="phone"
              label="手机号"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="客户姓名"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="gender"
              label="性别"
              width="60"
            >
              <template #default="{ row }">
                {{ formatGender(row.gender) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="age"
              label="年龄"
              width="60"
            ></el-table-column>

            <el-table-column
              prop="activityId"
              label="活动信息"
              width="150"
            >
              <template #default="{ row }">
                {{ formatActivityName(row.activityId) || '无' }}
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              width="150"
            ></el-table-column>
            <el-table-column
              prop="updateTime"
              label="更新时间"
              width="150"
            ></el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="{ row }">
                <el-button type="text" style="color: #27ae60;" @click="viewClue(row)">查看</el-button>
              </template>
            </el-table-column>
        </el-table>
      </div>

      <!-- 分页容器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="total, prev, pager, next, sizes, jumper"
          :total="totalCount"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 查看线索模态框 -->
    <el-dialog
      v-model="dialogVisible.viewClue"
      :title="`查看线索(线索ID:${currentClue.id})`"
      width="600px"
      center
    >
      <el-form label-width="100px">
        <div class="form-row">
          <el-form-item label="* 手机号:" required class="form-item">
            <el-input :value="currentClue.phone || currentClue.fullPhone" disabled></el-input>
          </el-form-item>
          <el-form-item label="渠道来源:" class="form-item">
            <el-input :value="formatChannel(currentClue.channel)" disabled></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="活动信息:" class="form-item">
            <el-input :value="formatActivityName(currentClue.activityId) || '无'" disabled></el-input>
          </el-form-item>
          <el-form-item label="客户姓名:" class="form-item">
            <el-input v-model="currentClue.name" disabled></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="性别:" class="form-item">
            <el-input :value="formatGender(currentClue.gender)" disabled></el-input>
          </el-form-item>
          <el-form-item label="年龄:" class="form-item">
            <el-input v-model.number="currentClue.age" disabled></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="微信号:" class="form-item">
            <el-input v-model="currentClue.wechat" placeholder="暂无信息" disabled></el-input>
          </el-form-item>
          <el-form-item label="QQ:" class="form-item">
            <el-input v-model="currentClue.qq" placeholder="暂无信息" disabled></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="意向学科:" class="form-item">
            <el-input :value="formatSubject(currentClue.interestedSubject || currentClue.subject)" disabled></el-input>
          </el-form-item>
          <el-form-item label="意向等级:" class="form-item">
            <div>
              <span :style="getLevelColorStyle(currentClue.interestLevel || currentClue.level)">
                {{ formatLevel(currentClue.interestLevel || currentClue.level) }}
              </span>
            </div>
          </el-form-item>
        </div>
      </el-form>
      
      <!-- 跟进历史 -->
      <div class="follow-history">
        <h4 style="margin: 20px 0 10px 0">跟进历史</h4>
        <el-table :data="processedTrackRecords" stripe size="small">
          <el-table-column label="意向等级" width="120">
            <template #default="scope">
              <span :style="getLevelColorStyle(scope.row.level || '')">
                {{ formatLevel(scope.row.level || "") || "-" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="意向学科" width="150">
            <template #default="scope">
              {{ formatSubject(scope.row.subject || "") || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="跟进人" width="100">
            <template #default="scope">
              {{ scope.row.assignName || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="跟进时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime || "") || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="下次跟进时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.nextTime || "") || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="跟进记录">
            <template #default="scope">
              {{ scope.row.record || "-" }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="dialogVisible.viewClue = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 分配线索模态框 -->
    <el-dialog
      v-model="dialogVisible.assignClue"
      :title="`分配线索(线索ID:${currentClue.id})`"
      width="500px"
      center
    >
      <el-form label-width="100px">
        <el-form-item label="手机号:" disabled>
          <el-input v-model="currentClue.phone" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户姓名:" disabled>
          <el-input v-model="currentClue.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="* 分配人员:" required>
          <el-select v-model="assignForm.userId" placeholder="请选择">
            <el-option 
              v-for="user in userList" 
              :key="user.value" 
              :label="user.label" 
              :value="user.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible.assignClue = false">取消</el-button>
        <el-button type="primary" @click="assignClueToUser">确认分配</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 调整盒模型 */
.clue-pool-view {
  padding: 20px;
  box-sizing: border-box;
}

/* 页面标题 */
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

/* 搜索条件区域 */
.search-container {
  background-color: #fff;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 20px;
}

/* 调整输入框和选择器的宽度 */
:deep(.el-input__wrapper) {
  min-width: 160px;
}

:deep(.el-select) {
  min-width: 160px;
}

/* 内容整体容器 */
.content-wrapper {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

/* 表格内容容器 */
.table-wrapper {
  overflow-x: auto; /* 允许水平滚动 */
  overflow-y: auto; /* 允许垂直滚动 */
  height: 400px; /* 固定高度确保滚动条出现 */
  border-bottom: 1px solid #ebeef5;
}

/* 分页容器 */
.pagination-wrapper {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  clear: both;
  position: relative;
  z-index: 10;
  box-sizing: border-box;
  width: 100%;
}

/* 调整表格样式 */
:deep(.el-table) {
  border-top: none;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #606266;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

/* 表单行布局 */
.form-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.form-item {
  flex: 1;
  min-width: 250px;
  margin-right: 20px;
  margin-bottom: 0 !important;
}

.form-item:last-child {
  margin-right: 0;
}

/* 跟进历史样式 */
.follow-history {
  margin-top: 20px;
}

.follow-history h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #303133;
}

.history-table {
  overflow-x: auto;
}

.history-table .el-table {
  font-size: 12px;
}

.history-table .el-table__row {
  height: 32px;
}

.history-table .el-table__header th,
.history-table .el-table__body td {
  padding: 6px 0;
}

:deep(.history-table .el-table) {
  border: 1px solid #ebeef5;
}

:deep(.history-table .el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

:deep(.history-table .el-table__row) {
  height: 40px;
}

:deep(.history-table .el-table__cell) {
  padding: 8px 12px;
  font-size: 14px;
}

/* 操作按钮间距 */
:deep(.el-table .el-button) {
  margin-right: 0;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .clue-pool-view {
    padding: 10px;
  }

  .search-container {
    padding: 15px;
  }

  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>